(function() {
    'use strict';

    angular
        .module('milkbeeApp')
        .controller('ModeratorDialogController', ModeratorDialogController);

    ModeratorDialogController.$inject = ['$timeout', '$scope','$http', '$stateParams', '$uibModalInstance', 'entity', 'Moderator'];

    function ModeratorDialogController ($timeout, $scope, $http,$stateParams, $uibModalInstance, entity, Moderator) {
        var vm = this;

        vm.moderator = entity;
        vm.clear = clear;
        vm.datePickerOpenStatus = {};
        vm.openCalendar = openCalendar;
        vm.save = save;
        vm.leaguers={};
        vm.categories={};
        vm.onLeaguersChange=onLeaguersChange;
        vm.onCategoryChange=onCategoryChange;
        $timeout(function (){
            angular.element('.form-group:eq(1)>input').focus();
        });

        function clear () {
            $uibModalInstance.dismiss('cancel');
        }

        function save () {
            vm.isSaving = true;
            if (vm.moderator.id !== null) {
                Moderator.update(vm.moderator, onSaveSuccess, onSaveError);
            } else {
                Moderator.save(vm.moderator, onSaveSuccess, onSaveError);
            }
        }

        function onSaveSuccess (result) {
            $scope.$emit('milkbeeApp:moderatorUpdate', result);
            $uibModalInstance.close(result);
            vm.isSaving = false;
        }

        function onSaveError () {
            vm.isSaving = false;
        }

        vm.datePickerOpenStatus.createdAt = false;

        function openCalendar (date) {
            vm.datePickerOpenStatus[date] = true;
        }
        
        function loadLeaguers(){
        	$http({
        		method: 'get',
        		url: '/api/allleaguers',
        		transformRequest: angular.identity
        	}).success(function(ret){
        		vm.leaguers=ret;
        	});
        }
        function loadCategories(){
        	$http({
        		method: 'get',
        		url: '/api/categoriesbylevel/1',
        		transformRequest: angular.identity
        	}).success(function(ret){
        		vm.categories=ret;
        	});
        }
       
        function onLeaguersChange(){
        	//vm.category.parentId=vm.parentCategory.id;
        	vm.moderator.leaguerId=vm.leaguer.id;
        }   
        function onCategoryChange(){
        	//vm.category.parentId=vm.parentCategory.id;
        	vm.moderator.categoryId=vm.category.id;
        }   
        loadLeaguers();
        loadCategories();
    }
})();
